package com.dz.basic.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dz.basic.entity.Item;
import com.dz.basic.service.ItemService;
import com.dz.basic.vo.ItemClassVO;

/**
 * <p>
 * 业务类型明细 前端控制器
 * </p>
 *
 * @author star
 * @since 2017-06-27
 */
@RestController
@Api(value="item",description="item集合")
public class ItemControler {

	@Autowired
	private ItemService itemService;

	@RequestMapping("/items")
	@ApiOperation(value="获取多个item",httpMethod="GET")
	public List<ItemClassVO> getByIds(@ApiParam(value="id集合逗号分隔",name="ids") @RequestParam("ids")  String ids) {
		if (StringUtils.isBlank(ids)) {
			throw new RuntimeException("id不能为空");
		}
		Wrapper<Item> itemWrapper = new EntityWrapper<Item>();
		itemWrapper.in("fitemclassid", ids);
		itemWrapper.orderBy("fitemclassid,fitemid");
		List<Item> items = itemService.selectList(itemWrapper);
		return contertBy(items, ids);
	}

	private List<ItemClassVO> contertBy(List<Item> items, String ids) {
		String[] classids = StringUtils.split(ids, ",");
		List<ItemClassVO> itemClassVOs = new ArrayList<ItemClassVO>(classids.length);
		Map<String, ItemClassVO> itemMap = new HashMap<String, ItemClassVO>();
		for (Item item : items) {
			String classTypeId = item.getItemclassid().toString();
			ItemClassVO itemClassVO = itemMap.get(classTypeId);
			if (itemClassVO == null) {
				itemClassVO = new ItemClassVO();
				itemClassVO.setItemClassDesc(item.getItemclassDesc());
				itemClassVO.setItemClassId(item.getItemclassid());
				itemClassVO.getChildList().add(item);
				itemMap.put(classTypeId, itemClassVO);
				itemClassVOs.add(itemClassVO);
			} else {
				itemClassVO.getChildList().add(item);
			}
		}
		return itemClassVOs;
	}
}
